import { Component} from '@angular/core';
import { Storage } from '@ionic/storage';
import { NavController,MenuController,ToastController,Platform} from 'ionic-angular';

import { JPushService } from 'ionic2-jpush';
import { CreateTask } from '../createtask/createtask';
import { TaskDetail } from '../taskdetail/taskdetail';
import { LoginPage } from '../login/login';
import { FilterPage } from '../filter/filter';
import { ApiService } from '../../providers/ApiService';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  categories = [
    {id: 1, name: '待处理', enabled: true, value:'pending',num:0},
    {id: 2, name: '已处理', enabled: true, value:'handled',num:0},
    {id: 3, name: '已完成', enabled: true, value:'completed',num:0}
  ]
  token='';
  page = 1
  list = [];
  username;
  push_id = null;
  noMoreArticleTip = false;
  statuslist = "pending";
  dealstatus = 1;
  contentflag = false;
  constructor(
    public navCtrl: NavController,
    public storage: Storage,
    private apiService: ApiService,
    public toastCtrl: ToastController,
    public menuCtrl: MenuController,
    private jPushPlugin: JPushService,
    private platform: Platform
  ){
    this.storage.get('mytoken').then((mytoken)=>{
      if(mytoken) {
        this.token = mytoken;
        this.getTaskLists({token:this.token,page:this.page,deal:this.dealstatus});
      }
    })
    this.storage.get('username').then((username)=>{
      if(username) {
        this.username = username;
      }
    })
    platform.ready().then( () =>{
      // 注册极光
      this.jPushPlugin.init()
        .then(res => {
          console.log(res,1)
          this.jPushPlugin.setApplicationIconBadgeNumber(0);//清除消息通知
        })
        .catch(err => console.log(err,2))
      /**
       * 获取ID
       */
      this.jPushPlugin.getRegistrationID()
        .then(res => {
          this.storage.set('pushid', res)
          console.log(res,3);
        })//接口需要的id
        .catch(err => console.log(err,4))
      //点击通知消息事件
      this.jPushPlugin.openNotification()
        .subscribe( res => {
          console.log(res);
          //进入详情页
          let id = null;
          let state = null;
          if(res.extras){
            id = res.extras.id;
            state = res.extras.classname ;
          }else{
            id = res.id;
            state = res.classname ;
          }
          this.navCtrl.push(TaskDetail, {
            id:id,
            state: state
          });
          this.jPushPlugin.setApplicationIconBadgeNumber(0);//清除消息通知
        })
      //收到通知消息
      this.jPushPlugin.receiveNotification()
        .subscribe( res => {
          console.log('收到推送');
          console.log(res)
        });
      //收到自定义消息
      this.jPushPlugin.receiveMessage()
        .subscribe( res => {
          console.log('收到推送');
          console.log(res)
        });
    })
  }
  ionViewDidEnter(){
    this.list = [];
    this.contentflag = false;
    this.storage.get('mytoken').then((mytoken)=>{
      if(mytoken) {
        this.token = mytoken;
        this.getTaskLists({token:this.token,page:this.page,deal:this.dealstatus});
      }
    })
  }
  //创建新任务
  creat_task(){
    this.navCtrl.push(CreateTask)
  }
  //进入任务详情页
  goTaskDetail(id,state){
    this.navCtrl.push(TaskDetail,{
      id:id,
      state: state
    })
  }
  dismissHandler() {
    //console.info('Toast onDidDismiss()');
  }
  //消息提示函数
  formTip(hint){
    const toast = this.toastCtrl.create({
      message: hint,
      duration: 3000,
      position: 'middle'
    });
    toast.onDidDismiss(this.dismissHandler);
    toast.present();
    return;
  }
  //修改任务
  modifyTask(status,createuser,task_id){
    if(status == '待接手' && createuser == this.username){
      this.navCtrl.push(CreateTask,{
        taskid:task_id
      })
    }else{
      this.formTip('您没有修改权限');
    }
  }
  //撤销任务
  revokeTask(status,createuser,task_id){
    if(status == '待接手' && createuser == this.username){
      this.apiService.taskOperations({token: this.token,taskid: task_id,action: 9},response => {
        if(response.json().status == 1){
          for(let i = 0;i <= this.list.length;i++){
            if(this.list[i].id == task_id){
              this.list.splice(i, 1);
            }
          }
          this.formTip(response.json().info);
        }else{
          this.formTip(response.json().info);
        }
      })
    }else{
      this.formTip('您没有修改权限');
    }
    this.getTaskLists({token:this.token,page:this.page,deal:this.dealstatus});
  }
  //提醒任务
  remindTask(status,createuser,task_id){
    if(status == '待接手' && createuser == this.username){
      this.apiService.remindTasks({token: this.token,taskid: task_id},response => {
        if(response.json().status == 1){
          this.formTip(response.json().info);
        }else{
          this.formTip(response.json().info);
        }
      })
    }else{
      this.formTip('您没有修改权限');
    }
  }

  //搜索
  filterItems(e){
    //let val = e.target.value;
    this.navCtrl.push(FilterPage)
  }
  //下拉刷新
  doRefresh(ionRefresh){
    this.list = [];
    this.page = 1;
    let body = {
      token:this.token,
      page:this.page,
      deal:this.dealstatus
    }
    this.getTaskLists(body,ionRefresh);
  }
  //上拉加载
  doInfinite(infiniteScroll){
     this.page++;
     let body = {
       token:this.token,
       page:this.page,
       deal:this.dealstatus
     }
     this.getTaskLists(body, infiniteScroll);
  }
  //登录
  login(){
    if(this.token == '' || this.token == undefined){
      this.navCtrl.push(LoginPage)
    }else{
      this.menuCtrl.toggle();
    }
  }
  //切换任务状态列表
  switchList(value,state){
    this.contentflag = false;
    this.statuslist = value;
    this.dealstatus = state;
    this.noMoreArticleTip = false;
    this.list = [];
    let body = {
      token: this.token,
      page: 1,
      deal: state
    }
    this.getTaskLists(body,null);
  }
  //获取任务列表
  getTaskLists(body,load = null) {
    this.apiService.getTaskStatusLists(body,response => {
      if(response.json().status == 1){
        let lists = response.json().content;
        this.categories[0].num = response.json().count.pending;
        this.categories[1].num = response.json().count.handled;
        this.categories[2].num = response.json().count.completed;
        if(lists == null && body.page == 1){
          this.contentflag = true;
        }
        if (lists != null && lists.length > 0) {
          if (this.page == 1) {
            this.list = lists
          } else {
            this.list = this.list.concat(lists)
          }
        }else{
          load.complete();
          load.enable(false);
          this.noMoreArticleTip = true;
        }
      }else{
        let error = response.json().info
        this.formTip(error)
        //this.toastOrToLogin(error, error == '参数错误，token错误')
      }
      load.complete();
    })
  }
}
